<template>
    <el-upload ref="myUpload" v-bind="attrs" class="avatar-uploader" :action="action" :headers="headers" :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :on-change="handleChange"
        :on-error="handleError">
        <!-- <img v-if="modelValue && type === 'img'" :src="modelValue" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon> -->
        <slot></slot>
    </el-upload>
</template>

<script lang="ts" setup>
import Cookie from 'js-cookie';
import { ElMessage, UploadProps } from 'element-plus';
import { useAttrs, ref, computed, nextTick } from 'vue';

const action = computed(() =>  import.meta.env.VITE_URL + (props.url ? props.url  : '/ips/file/upload'))
 ;const headers = {
    token: Cookie.get('token'),
};
const myUpload = ref(null)
const attrs = useAttrs()

const props = withDefaults(defineProps<{
    modelValue: string,
    url:string,
    type?: 'img' | 'file',
}>(), {
    type: 'img'
});

const emit = defineEmits<{
    (e: 'update:modelValue', val: string): void,
    (e: 'change', val: string, val2: string): void
    (e: 'fileChange', fileName: string): void
    (e: 'error', fileName: string): void
}>();

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {

    if(response.code == 0 ) {
        emit('update:modelValue', response.data);

        emit('success', uploadFile.name, response.data);
    } else {
        ElMessage.error(response.msg);
        myUpload.value.clearFiles()
        emit('error');
    }
    myUpload.value.clearFiles() // 先删除选择的文件
    nextTick(() => {
    // file里面的raw就是File类型，直接复制给组件
        myUpload.value.handleStart(uploadFile.raw) // 重新赋值原来的文件
     })

};

const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles,) => {
    console.log(uploadFiles)
    if(uploadFiles.length > 1) {
        uploadFiles.shift()
    }
    emit('fileChange', uploadFile.name);
}

const handleError: UploadProps['onChange'] = (uploadFile, uploadFiles,) => {
    console.log(uploadFiles)
    // if(uploadFiles.length > 1) {
    //     uploadFiles.shift()
    // }
    // emit('fileChange', uploadFile.name);
}

const submit = () => {
    myUpload.value!.submit()
}
defineExpose({
    submit
})
</script>

<style lang='scss' scoped>
.avatar-uploader .avatar {
    width: 64px;
    height: 64px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 64px;
    height: 64px;
    text-align: center;
    border: 1px solid rgba(0, 83, 176, 0.6);
    margin: 15px 0 24px 0;
}
:deep(.el-icon.avatar-uploader-icon){
    margin: 0
}
</style>

